package org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.persistence;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import org.framework.lazy.cloud.network.heartbeat.common.ChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.RouteContext;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.RouteType;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.ServerProxyRoute;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.entity.LazyNettyServerRouteDO;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.converter.LazyNettyServerRouteConverter;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.server.route.LazyNettyServerRouteRepository;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.entity.LazyNettyServerVirtualRouteDO;
import org.springframework.stereotype.Repository;

import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

import org.wu.framework.core.NormalUsedString;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazyUpdateSetValueWrappers;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazyWrappers;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;
import jakarta.annotation.Resource;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.server.route.LazyNettyServerRoute;
import org.wu.framework.lazy.orm.database.lambda.stream.lambda.LazyLambdaStream;
import java.util.List;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
/**
 * describe 服务端路由 
 *
 * @author Jia wei Wu
 * @date 2025/04/05 09:00 晚上
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyInfrastructurePersistence 
 **/
@Repository
public class LazyNettyServerRouteRepositoryImpl  implements  LazyNettyServerRouteRepository {

    @Resource
    LazyLambdaStream lazyLambdaStream;

    /**
     * describe 新增服务端路由
     *
     * @param lazyNettyServerRoute 新增服务端路由     
     * @return {@link Result<LazyNettyServerRoute>} 服务端路由新增后领域对象     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<LazyNettyServerRoute> story(LazyNettyServerRoute lazyNettyServerRoute) {
        LazyNettyServerRouteDO lazyNettyServerRouteDO = LazyNettyServerRouteConverter.INSTANCE.fromLazyNettyServerRoute(lazyNettyServerRoute);
        lazyLambdaStream.upsert(lazyNettyServerRouteDO);
        String routeIp = lazyNettyServerRoute.getRouteIp();
        String routePort = NormalUsedString.ASTERISK;
        // 新增虚拟ip映射
        LazyNettyServerVirtualRouteDO lazyNettyServerVirtualRouteDO = new LazyNettyServerVirtualRouteDO();
        lazyNettyServerVirtualRouteDO.setIsDeleted(false);
        lazyNettyServerVirtualRouteDO.setVirtualIp(routeIp);
        lazyNettyServerVirtualRouteDO.setVirtualPort(routePort);
        lazyNettyServerVirtualRouteDO.setTargetIp(routeIp);
        lazyNettyServerVirtualRouteDO.setTargetPort(routePort);
        lazyLambdaStream.upsert(lazyNettyServerVirtualRouteDO);

        // 更新服务端路由

        ServerProxyRoute serverProxyRoute = new ServerProxyRoute();
        serverProxyRoute.setServerIp("default");
        serverProxyRoute.setVirtualIp(routeIp);
        serverProxyRoute.setVirtualPort(routePort);
        serverProxyRoute.setTargetIp(routeIp);
        serverProxyRoute.setTargetPort(routePort);
        serverProxyRoute.setRouteType(RouteType.LOCAL);
        RouteContext.setRoute(serverProxyRoute);

        ServerProxyRoute clientProxyServerRoute = new ServerProxyRoute();
        clientProxyServerRoute.setServerIp("default");
        clientProxyServerRoute.setVirtualIp(routeIp);
        clientProxyServerRoute.setVirtualPort(routePort);
        clientProxyServerRoute.setTargetIp(routeIp);
        clientProxyServerRoute.setTargetPort(routePort);
        clientProxyServerRoute.setRouteType(RouteType.CLIENT_PROXY_SEVER);
        // 发送所有客户端本地路由刷新
        ChannelContext.getChannels().forEach((clientId, channels) -> {
            NettyProxyMsg nettyMsg = new NettyProxyMsg();
            nettyMsg.setType(ProxyMessageType.HTTP_DISTRIBUTE_CLIENT_PROXY_SERVER_SERVER_ROUTE_);
            nettyMsg.setData((JSON.toJSONString(clientProxyServerRoute)
                    .getBytes(StandardCharsets.UTF_8)));
            // 发送所有客户端ID
            for (Channel channel : channels) {
                channel.writeAndFlush(nettyMsg);
            }
        });

        return ResultFactory.successOf();
    }

    /**
     * describe 批量新增服务端路由
     *
     * @param lazyNettyServerRouteList 批量新增服务端路由     
     * @return {@link Result<List<LazyNettyServerRoute>>} 服务端路由新增后领域对象集合     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<List<LazyNettyServerRoute>> batchStory(List<LazyNettyServerRoute> lazyNettyServerRouteList) {
        List<LazyNettyServerRouteDO> lazyNettyServerRouteDOList = lazyNettyServerRouteList.stream().map(LazyNettyServerRouteConverter.INSTANCE::fromLazyNettyServerRoute).collect(Collectors.toList());
        lazyLambdaStream.upsert(lazyNettyServerRouteDOList);
        return ResultFactory.successOf();
    }

    /**
     * describe 查询单个服务端路由
     *
     * @param lazyNettyServerRoute 查询单个服务端路由     
     * @return {@link Result<LazyNettyServerRoute>} 服务端路由领域对象     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<LazyNettyServerRoute> findOne(LazyNettyServerRoute lazyNettyServerRoute) {
        LazyNettyServerRouteDO lazyNettyServerRouteDO = LazyNettyServerRouteConverter.INSTANCE.fromLazyNettyServerRoute(lazyNettyServerRoute);
        LazyNettyServerRoute lazyNettyServerRouteOne = lazyLambdaStream.selectOne(LazyWrappers.lambdaWrapperBean(lazyNettyServerRouteDO), LazyNettyServerRoute.class);
        return ResultFactory.successOf(lazyNettyServerRouteOne);
    }

    /**
     * describe 查询多个服务端路由
     *
     * @param lazyNettyServerRoute 查询多个服务端路由     
     * @return {@link Result<List<LazyNettyServerRoute>>} 服务端路由领域对象     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<List<LazyNettyServerRoute>> findList(LazyNettyServerRoute lazyNettyServerRoute) {
        LazyNettyServerRouteDO lazyNettyServerRouteDO = LazyNettyServerRouteConverter.INSTANCE.fromLazyNettyServerRoute(lazyNettyServerRoute);
        List<LazyNettyServerRoute> lazyNettyServerRouteList = lazyLambdaStream.selectList(LazyWrappers.lambdaWrapperBean(lazyNettyServerRouteDO), LazyNettyServerRoute.class);
        return ResultFactory.successOf(lazyNettyServerRouteList);
    }

    /**
     * describe 分页查询多个服务端路由
     *
     * @param size 当前页数
     * @param current 当前页
     * @param lazyNettyServerRoute 分页查询多个服务端路由     
     * @return {@link Result<LazyPage<LazyNettyServerRoute>>} 分页服务端路由领域对象     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<LazyPage<LazyNettyServerRoute>> findPage(int size,int current,LazyNettyServerRoute lazyNettyServerRoute) {
        LazyNettyServerRouteDO lazyNettyServerRouteDO = LazyNettyServerRouteConverter.INSTANCE.fromLazyNettyServerRoute(lazyNettyServerRoute);
        LazyPage<LazyNettyServerRoute> lazyPage = new LazyPage<>(current,size);
        LazyPage<LazyNettyServerRoute> lazyNettyServerRouteLazyPage = lazyLambdaStream.selectPage(LazyWrappers.lambdaWrapperBean(lazyNettyServerRouteDO),lazyPage, LazyNettyServerRoute.class);
        return ResultFactory.successOf(lazyNettyServerRouteLazyPage);
    }

    /**
     * describe 删除服务端路由
     *
     * @param lazyNettyServerRoute 删除服务端路由     
     * @return {@link Result<LazyNettyServerRoute>} 服务端路由     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<LazyNettyServerRoute> remove(LazyNettyServerRoute lazyNettyServerRoute) {
        lazyLambdaStream.update(LazyUpdateSetValueWrappers.<LazyNettyServerRouteDO>lambdaWrapper()
                        .set(LazyNettyServerRouteDO::getIsDeleted, true),
                LazyWrappers
                        .<LazyNettyServerRouteDO>lambdaWrapper()
                        .eq(LazyNettyServerRouteDO::getId, lazyNettyServerRoute.getId())

        );

        LazyNettyServerRouteDO serverRouteDO = lazyLambdaStream.selectOne(
                LazyWrappers.<LazyNettyServerRouteDO>lambdaWrapper()
                        .eq(LazyNettyServerRouteDO::getId, lazyNettyServerRoute.getId())
        );
        String routeIp = serverRouteDO.getRouteIp();
        String routePort = NormalUsedString.ASTERISK;

        ServerProxyRoute clientProxyServerRoute = new ServerProxyRoute();
        clientProxyServerRoute.setServerIp("default");
        clientProxyServerRoute.setVirtualIp(routeIp);
        clientProxyServerRoute.setVirtualPort(routePort);
        clientProxyServerRoute.setTargetIp(routeIp);
        clientProxyServerRoute.setTargetPort(routePort);
        clientProxyServerRoute.setRouteType(RouteType.CLIENT_PROXY_SEVER);
        // 发送所有客户端本地路由刷新
        ChannelContext.getChannels().forEach((clientId, channels) -> {
            NettyProxyMsg nettyMsg = new NettyProxyMsg();
            nettyMsg.setType(ProxyMessageType.HTTP_DISTRIBUTE_CLIENT_PROXY_SERVER_SERVER_ROUTE_CLOSE_);
            nettyMsg.setData((JSON.toJSONString(clientProxyServerRoute)
                    .getBytes(StandardCharsets.UTF_8)));
            // 发送所有客户端ID
            for (Channel channel : channels) {
                channel.writeAndFlush(nettyMsg);
            }
        });
        return ResultFactory.successOf();
    }

    /**
     * describe 是否存在服务端路由
     *
     * @param lazyNettyServerRoute 服务端路由领域对象     
     * @return {@link Result<Boolean>} 是否存在 true 存在，false 不存在     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<Boolean> exists(LazyNettyServerRoute lazyNettyServerRoute) {
        LazyNettyServerRouteDO lazyNettyServerRouteDO = LazyNettyServerRouteConverter.INSTANCE.fromLazyNettyServerRoute(lazyNettyServerRoute);
        Boolean exists=lazyLambdaStream.exists(LazyWrappers.lambdaWrapperBean(lazyNettyServerRouteDO));
        return ResultFactory.successOf(exists);
    }

}